<template>
  <div
    style="display: flex; flex-direction: row; justify-content: space-between"
  >
    <SearchForm :configs="formConfig" :search="handleSearch" />
    <div style="display: flex; flex-direction: row;">
      <ExportButton
        :params="{
          startDate: state.searchParams?.dateRange[0],
          endDate: state.searchParams?.dateRange[1]
        }"
        :path="PRODUCT_ORDER_EXPORT_PATH"
        :fileName="PRODUCT_ORDER_EXPORT_FILE_NAME"
      />
    </div>
  </div>
  <el-table :data="state.tableData" border style="width: 100%">
    <el-table-column prop="index" label="序号" width="60px">
      <template #default="scope">
        {{ (state.pageNum - 1) * state.pageSize + scope.$index + 1 }}
      </template>
    </el-table-column>
    <el-table-column prop="orderNumber" label="订单编号" />
    <el-table-column prop="wxUserPhoneNumber" label="用户账号" />
    <el-table-column prop="transactionAmount" label="支付类型" width="100">
      <template #default="scope">
        <div v-if="scope.row.paymentMode === 'points'">积分支付</div>
        <div v-else>微信支付</div>
      </template>
    </el-table-column>
    <el-table-column prop="transactionAmount" label="订单金额" width="240">
      <template #default="scope">
        <div v-if="scope.row.paymentMode === 'points'">
          {{ scope.row.transactionPoints }}积分
        </div>
        <div v-else>{{ scope.row.transactionAmount }}元</div>
      </template>
    </el-table-column>
    <!-- <el-table-column prop="transactionAmount" label="订单金额" width="240">
      <template #default="scope">
        <div
          v-if="state.editPrice && state.editPriceIndex === scope.$index"
          class="flex-line"
        >
          <el-input-number
            v-model="state.newPrice"
            :precision="2"
            :min="0.01"
          />
          <el-icon
            class="edit-price-icon"
            @click="submitEditPrice(scope.row.orderNumber)"
            ><CircleCheck
          /></el-icon>
          <el-icon class="edit-price-icon" @click="cancelEditPrice"
            ><CircleClose
          /></el-icon>
        </div>
        <div v-else>{{ scope.row.transactionAmount }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="salesman" label="销售人" /> -->
    <el-table-column prop="orderStatus" label="订单状态" width="120">
      <template #default="scope">
        <el-tag
          type="success"
          v-show="scope.row.orderStatus === OrderStatusEnum.SUCCESS"
          >支付成功</el-tag
        >
        <el-tag
          type="info"
          v-show="scope.row.orderStatus === OrderStatusEnum.PENDING_PAYMENT"
          >待支付</el-tag
        >
        <el-tag
          type="danger"
          v-show="scope.row.orderStatus === OrderStatusEnum.FAILURE"
          >支付失败</el-tag
        >
        <el-tag
          type="warning"
          v-show="scope.row.orderStatus === OrderStatusEnum.CANCELED"
          >超时取消</el-tag
        >
        <el-tag
          v-show="scope.row.orderStatus === OrderStatusEnum.PENDING_DELIVER"
          >待发货</el-tag
        >
        <el-tag
          type="info"
          v-show="scope.row.orderStatus === OrderStatusEnum.PENDING_RECEIVED"
          >已发货</el-tag
        >
        <el-tag
          type="info"
          v-show="scope.row.orderStatus === OrderStatusEnum.COMPLETED"
          >订单完成</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column prop="qrCodeStatus" label="二维码状态" align="center" width="100">
      <template #default="scope">
        <el-tag
          type="info"
          v-show="scope.row.qrCodeStatus === QrCodeStatusEnum.COMPLETED">已使用</el-tag
        >
        <el-tag
          type="success"
          v-show="scope.row.qrCodeStatus === QrCodeStatusEnum.PENDING">未使用</el-tag
        >
        <div v-show="!scope.row.qrCodeStatus">-</div>
      </template>
    </el-table-column>
    <el-table-column prop="refundStatus" label="申请退款" align="center" width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.productRefundInfoDto?.refundStatus" type="warning">已申请</el-tag>
        <div v-else>-</div>
      </template>
    </el-table-column>
    <el-table-column prop="refundApplyReason" label="退款原因" align="center">
      <template #default="scope">
        <div v-if="scope.row.productRefundInfoDto?.refundApplyReason">
          {{ scope.row.productRefundInfoDto?.refundApplyReason }}
        </div>
        <div v-else>-</div>
      </template>
    </el-table-column>
    <el-table-column prop="orderStatus" label="退款状态" align="center">
      <template #default="scope">
        <el-tag v-show="scope.row.refundAmount === scope.row.transactionAmount"
          >全部退款</el-tag
        >
        <el-tag
          type="warning"
          v-show="
            scope.row.refundAmount > 0 &&
            scope.row.refundAmount < scope.row.transactionAmount
          "
          >部分退款</el-tag
        >
        <div v-show="scope.row.refundAmount === 0">-</div>
      </template>
    </el-table-column>
    <!-- <el-table-column prop="orderStatus" label="退款状态" align="center">
      <template #default="scope">
        <el-tag v-show="scope.row.refundAmount === scope.row.transactionAmount"
          >全部退款</el-tag
        >
        <el-tag
          type="warning"
          v-show="
            scope.row.refundAmount > 0 &&
            scope.row.refundAmount < scope.row.transactionAmount
          "
          >部分退款</el-tag
        >
        <div v-show="scope.row.refundAmount === 0">-</div>
      </template>
    </el-table-column> -->
    <el-table-column prop="orderTimeNodeInfo.orderDate" label="提交时间" />
    <el-table-column label="操作" width="320" fixed="right">
      <template #default="scope">
        <OrderInfodialog :orderInfo="scope.row" />
        <DeliveryDialog
          :orderInfo="scope.row"
          :updateList="fetchList"
          v-show="enableHandleRefund(scope.row) > 0"
        />
        <!-- <el-button 
          type="primary" 
          v-show="scope.row.orderStatus === OrderStatusEnum.PENDING_PAYMENT" 
          @click="editOrderPrice(scope.row, scope.$index)"
        >改价</el-button> -->
        <el-button
          type="primary"
          v-show="
            [
              OrderStatusEnum.SUCCESS,
              OrderStatusEnum.PENDING_DELIVER,
              OrderStatusEnum.PENDING_RECEIVED,
              OrderStatusEnum.COMPLETED,
            ].includes(scope.row.orderStatus) &&
            enableHandleRefund(scope.row) > 0
          "
          @click="refund(scope.row)"
          >退款</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="dialogVisible" title="退款" width="500">
    <el-input-number
      v-model="refundItem.refundAmount"
      :precision="2"
      :min="0.01"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleConfirmRefund">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <Pagination
    :total="state.total"
    :limit="state.pageSize"
    :page-change="PageChange"
  />
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import DeliveryDialog from "./deliveryDialog.vue";
import OrderInfodialog from "./orderInfodialog.vue";
import SearchForm from "@/components/SearchForm/index.vue";
import Pagination from "@/components/pagination/index.vue";
import { findOrderProductList, refundAmount } from "@/api/shop";
import { OrderStatusEnum, QrCodeStatusEnum } from "./config";
import { ElMessage } from "element-plus";
import {
  PRODUCT_ORDER_EXPORT_PATH,
  PRODUCT_ORDER_EXPORT_FILE_NAME,
} from "@/components/ExportButton/config";
import ExportButton from "@/components/ExportButton/index.vue";

const state = reactive<any>({
  tableData: [],
  total: 0,
  pageNum: 1,
  pageSize: 10,
  searchParams: {
    dateRange: []
  },
  editPrice: false, // 是否正在改价
  editPriceIndex: -1,
  newPrice: ""
});
const dialogVisible = ref(false);
const refundItem = ref({
  orderNumber: "",
  refundAmount: 0.01,
});

const formConfig = [
  {
    label: "订单编号",
    value: "orderNumber",
  },
  {
    label: "收货人",
    value: "receiverIdName",
  },
  {
    label: "提交日期",
    value: "dateRange",
    type: "daterange",
  },
];

const enableHandleRefund = (row: any) =>
  row.transactionAmount - (row.refundAmount || 0);

const handleSearch = (params: any) => {
  state.searchParams = params;
  fetchList();
};

const fetchList = () => {
  findOrderProductList({
    pageNum: state.pageNum,
    pageSize: state.pageSize,
    extraParamMap: {
      orderNumber: state.searchParams.orderNumber,
      receiverIdName: state.searchParams.receiverIdName,
      startDate: state.searchParams?.dateRange[0],
      endDate: state.searchParams?.dateRange[1]
    },
  }).then((res) => {
    state.tableData = res.data.rows || [];
    state.total = res.data.total;
  });
};
fetchList();

// 待支付订单改价
// const editOrderPrice = (row: any, index: number) => {
//   state.editPrice = true
//   state.editPriceIndex = index
//   state.newPrice = row.transactionAmount
// }

// 一键退款
const refund = (row: any) => {
  // console.log("🚀 ~ refund ~ row:", row)
  dialogVisible.value = true;
  refundItem.value = {
    orderNumber: row.orderNumber,
    refundAmount: row.transactionAmount,
  };
};

const handleConfirmRefund = () => {
  refundAmount(refundItem.value).then(() => {
    ElMessage.success("退款成功");
    fetchList();
    dialogVisible.value = false;
  });
};

// const submitEditPrice = (orderNumber: string) => {
//   state.editPrice = false;
//   modifyOrderAmount({
//     orderNumber: orderNumber,
//     transactionAmount: state.newPrice,
//   })
//     .then(() => {
//       ElMessage.success("改价成功");
//       fetchList();
//       state.editPrice = false;
//     })
//     .catch(() => {
//       state.editPrice = false;
//     });
// };

// const cancelEditPrice = () => {
//   state.editPrice = false;
// };

// 分页
const PageChange = (page: number) => {
  state.pageNum = page;
  fetchList();
};
</script>
<style lang="scss" scoped>
.flex-line {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.edit-price-icon {
  font-size: 20px;
  margin-left: 8px;
  cursor: pointer;
}
</style>
